// 全选/取消全选功能
function toggleSelectAll() {
    const selectAllCheckbox = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.tag-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.checked = selectAllCheckbox.checked;
    });
    toggleBatchDeleteButton();
}

// 根据选中状态启用/禁用批量删除按钮
function toggleBatchDeleteButton() {
    const checkboxes = document.querySelectorAll('.tag-checkbox:checked');
    const batchDeleteBtn = document.getElementById('batchDeleteBtn');
    batchDeleteBtn.disabled = checkboxes.length === 0;
}

// 提交批量删除表单
async function submitBatchDelete() {
    const checkboxes = document.querySelectorAll('.tag-checkbox:checked');
    if (checkboxes.length === 0) {
        createNotification('请选择要删除的标签', 'error');
        return;
    }
    
    const selectedCount = checkboxes.length;
    const batchDeleteBtn = document.getElementById('batchDeleteBtn');
    
    // 个性化确认提示
    if (confirm(`确定要删除选中的 ${selectedCount} 个标签吗？\n此操作无法撤销。`)) {
        // 显示加载状态
        batchDeleteBtn.disabled = true;
        batchDeleteBtn.textContent = '删除中...';
        
        // 获取选中的行元素
        const selectedRows = Array.from(checkboxes).map(cb => cb.closest('tr'));
        
        try {
            // 使用Fetch API发送批量删除请求
            const formData = new FormData();
            checkboxes.forEach(cb => formData.append('tag_ids', cb.value));
            
            const response = await fetch('/admin/tags/batch-delete', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });
            
            // 解析JSON响应
            const result = await response.json();
            
            if (result.success) {
                // 对每个选中的行添加动画效果
                selectedRows.forEach((row, index) => {
                    setTimeout(() => {
                        row.style.backgroundColor = '#ffeaa7';
                        row.style.transition = 'all 0.5s ease';
                        
                        setTimeout(() => {
                            row.style.opacity = '0';
                            row.style.transform = 'translateX(50px)';
                            
                            setTimeout(() => {
                                row.remove();
                                
                                // 最后一个元素动画完成后显示通知
                                if (index === selectedRows.length - 1) {
                                    createNotification(`成功删除 ${selectedCount} 个标签！`);
                                    
                                    // 恢复按钮状态
                                    batchDeleteBtn.disabled = false;
                                    batchDeleteBtn.textContent = '批量删除';
                                    
                                    // 重置全选复选框
                                    document.getElementById('selectAll').checked = false;
                                    
                                    // 检查是否还有数据行
                                    const remainingRows = document.querySelectorAll('tbody tr');
                                    if (remainingRows.length === 0) {
                                        // 如果没有数据了，刷新页面以显示空状态
                                        setTimeout(() => {
                                            location.reload();
                                        }, 1000);
                                    }
                                }
                            }, 300);
                        }, 100);
                    }, index * 100); // 错开动画时间，形成级联效果
                });
            } else {
                // 恢复按钮状态
                batchDeleteBtn.disabled = false;
                batchDeleteBtn.textContent = '批量删除';
                // 显示错误通知
                createNotification(result.message || '批量删除失败', 'error');
            }
        } catch (error) {
            // 恢复按钮状态
            batchDeleteBtn.disabled = false;
            batchDeleteBtn.textContent = '批量删除';
            // 显示错误通知
            createNotification('批量删除失败，请稍后重试', 'error');
        }
    }
}

// 创建自定义提示消息元素
function createNotification(message, type = 'success') {
    // 移除已存在的通知
    const existingNotification = document.getElementById('customNotification');
    if (existingNotification) {
        existingNotification.remove();
    }
    
    // 创建新通知元素
    const notification = document.createElement('div');
    notification.id = 'customNotification';
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 25px;
        border-radius: 6px;
        color: white;
        font-weight: 500;
        z-index: 10000;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        transition: all 0.3s ease;
        transform: translateX(100%);
        max-width: 300px;
    `;
    
    // 设置颜色
    if (type === 'success') {
        notification.style.backgroundColor = '#2ecc71';
    } else if (type === 'error') {
        notification.style.backgroundColor = '#e74c3c';
    }
    
    notification.textContent = message;
    document.body.appendChild(notification);
    
    // 显示通知
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 10);
    
    // 3秒后隐藏通知
    setTimeout(() => {
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

// 单个标签删除功能
function setupDeleteButtons() {
    document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', async (e) => {
            e.preventDefault();
            const tagId = btn.getAttribute('data-id');
            const tagName = btn.getAttribute('data-name');
            
            // 个性化确认提示
            if (confirm(`确定要删除标签 "${tagName}" 吗？\n此操作无法撤销。`)) {
                // 禁用按钮并显示加载状态
                btn.disabled = true;
                btn.textContent = '删除中...';
                
                try {
                    // 使用Fetch API发送请求
                    const response = await fetch(`/admin/tags/delete/${tagId}`, {
                        method: 'POST',
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest'
                        }
                    });
                    
                    // 解析JSON响应
                    const result = await response.json();
                    
                    if (result.success) {
                        // 获取当前行元素
                        const row = btn.closest('tr');
                        
                        // 添加高亮动画
                        row.style.backgroundColor = '#ffeaa7';
                        row.style.transition = 'all 0.5s ease';
                        
                        setTimeout(() => {
                            // 添加滑动动画
                            row.style.opacity = '0';
                            row.style.transform = 'translateX(50px)';
                            
                            setTimeout(() => {
                                // 移除行元素
                                row.remove();
                                // 显示成功通知
                                createNotification(`标签 "${tagName}" 删除成功！`);
                                
                                // 检查是否还有数据行
                                const remainingRows = document.querySelectorAll('tbody tr');
                                if (remainingRows.length === 0) {
                                    // 如果没有数据了，刷新页面以显示空状态
                                    setTimeout(() => {
                                        location.reload();
                                    }, 1000);
                                }
                            }, 300);
                        }, 100);
                    } else {
                        // 恢复按钮状态
                        btn.disabled = false;
                        btn.textContent = '删除';
                        // 显示错误通知
                        createNotification(result.message || '删除失败', 'error');
                    }
                } catch (error) {
                    // 恢复按钮状态
                    btn.disabled = false;
                    btn.textContent = '删除';
                    // 显示错误通知
                    createNotification('删除失败，请稍后重试', 'error');
                }
            }
        });
    });
}

// 状态切换功能
function setupStatusToggleButtons() {
    document.querySelectorAll('.toggle-status-btn').forEach(btn => {
        btn.addEventListener('click', async (e) => {
            e.preventDefault();
            const tagId = btn.getAttribute('data-id');
            const currentStatus = btn.getAttribute('data-status') === 'true';
            const targetStatus = !currentStatus;
            const confirmText = targetStatus ? '确定要启用此标签吗？' : '确定要禁用此标签吗？';
            
            if (confirm(confirmText)) {
                // 禁用按钮并显示加载状态
                btn.disabled = true;
                btn.textContent = '处理中...';
                
                try {
                    // 使用Fetch API发送请求
                    const response = await fetch(`/admin/tags/toggle-status/${tagId}`, {
                        method: 'POST',
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ new_status: targetStatus })
                    });
                    
                    // 解析JSON响应
                    const result = await response.json();
                    
                    if (result.success) {
                        // 使用后端返回的new_status更新按钮的data-status属性
                    btn.setAttribute('data-status', result.new_status.toString());
                    
                    // 更新按钮样式和文本
                    btn.className = 'btn btn-xs ' + (result.new_status ? 'btn-warning' : 'btn-success') + ' toggle-status-btn';
                    btn.textContent = result.new_status ? '禁用' : '启用';
                    
                    // 更新状态显示文本
                    const statusSpan = btn.previousElementSibling;
                    if (statusSpan) {
                        statusSpan.textContent = result.new_status ? '启用' : '禁用';
                        statusSpan.style.color = result.new_status ? '#2ecc71' : '#e74c3c';
                    }
                    
                    // 恢复按钮可用状态
                    btn.disabled = false;
                        
                    createNotification(result.message || '状态更新成功', 'success');
                    } else {
                        // 恢复按钮状态
                        btn.disabled = false;
                        btn.textContent = targetStatus ? '启用' : '禁用';
                        // 显示错误通知
                        createNotification(result.message || '状态更新失败', 'error');
                    }
                } catch (error) {
                    // 恢复按钮状态
                    btn.disabled = false;
                    btn.textContent = targetStatus ? '启用' : '禁用';
                    // 显示错误通知
                    createNotification('状态切换失败，请稍后重试', 'error');
                }
            }
        });
    });
}

// 为所有删除按钮添加点击事件监听器
document.addEventListener('DOMContentLoaded', function() {
    // 为全选框添加事件监听
    const selectAllCheckbox = document.getElementById('selectAll');
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', toggleSelectAll);
    }
    
    // 为所有复选框添加事件监听
    const checkboxes = document.querySelectorAll('.tag-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', toggleBatchDeleteButton);
    });
    
    // 为批量删除按钮添加事件监听
    const batchDeleteBtn = document.getElementById('batchDeleteBtn');
    if (batchDeleteBtn) {
        batchDeleteBtn.addEventListener('click', submitBatchDelete);
    }
    
    setupDeleteButtons();
    
    // 初始化状态切换功能
    setupStatusToggleButtons();
    
    // 检查URL参数中是否有message
    const urlParams = new URLSearchParams(window.location.search);
    const message = urlParams.get('message');
    if (message) {
        createNotification(message);
    }
});